import { useState } from 'react'
import { getUserListBySearch } from '@/api/user'
export interface IUserType {
  id: number
  phone: string
  name: string
  orgId: string
  workId: string
}
const useSearchUser = () => {
  let UserTimeout: ITimeoutType
  const [UserOptions, setUserOptions] = useState<IOptionItem[]>([])
  const handleSearchUser = (newValue = '') => {
    if (UserTimeout) {
      clearTimeout(UserTimeout)
      UserTimeout = null
    }
    const getOptions = async () => {
      const res = await getUserListBySearch<IUserType>({
        keyword: newValue,
      })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: (item.workId ? item.workId + '-' : '') + item.name,
              phone: item.phone,
              value: item.id + '',
              orgId: item.orgId,
              workId: item.workId,
            }
          }) || []
        setUserOptions(data)
      }
    }
    UserTimeout = setTimeout(getOptions, 500)
  }
  return { UserOptions, setUserOptions, handleSearchUser }
}

export default useSearchUser
